package cn.wbu.zyh.service.impl;

import cn.wbu.zyh.dto.VersionDTO;
import cn.wbu.zyh.service.VersionService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class VersionServiceImpl implements VersionService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String ARTICLE_VERSION_PREFIX = "article:version:";

    @Override
    public void saveVersion(Long articleId, String yDocState, String title) {
        String versionKey = ARTICLE_VERSION_PREFIX + articleId + ":" + System.currentTimeMillis();
        // 推荐以JSON存储
        Map<String, String> versionInfo = new HashMap<>();
        versionInfo.put("yDocState", yDocState);
        versionInfo.put("title", title);
        stringRedisTemplate.opsForValue().set(versionKey, JSON.toJSONString(versionInfo));
        stringRedisTemplate.expire(versionKey, 7, TimeUnit.DAYS);
    }

    @Override
    public String getVersion(Long articleId, Long versionTimestamp) {
        String versionKey = ARTICLE_VERSION_PREFIX + articleId + ":" + versionTimestamp;
        return stringRedisTemplate.opsForValue().get(versionKey);
    }

    @Override
    public List<VersionDTO> getAllVersions(Long articleId) {
        String pattern = ARTICLE_VERSION_PREFIX + articleId + ":*";
        Set<String> keys = stringRedisTemplate.keys(pattern);

        List<VersionDTO> versions = new ArrayList<>();
        if (keys != null) {
            for (String key : keys) {
                String jsonStr = stringRedisTemplate.opsForValue().get(key);
                if (jsonStr != null) {
                    Map<String, String> data = JSON.parseObject(jsonStr, new TypeReference<Map<String, String>>() {
                    });
                    String yDocState = data.get("yDocState");
                    String title = data.get("title");
                    Long versionTimestamp = Long.parseLong(key.substring(key.lastIndexOf(":") + 1));
                    versions.add(new VersionDTO(versionTimestamp, yDocState, title));
                }
            }
            // 推荐按时间戳排序（倒序显示最新版本在前）
            versions.sort((v1, v2) -> Long.compare(v2.getVersionTimestamp(), v1.getVersionTimestamp()));
        }
        return versions;
    }
}
